<template>
  <div class="mb-select van-cell van-cell-clear" v-show="visible">
    <van-cell 
      :title="title" 
      :is-link="!readonly"
      :value="value_display || (readonly ? '' : placeholder)" 
      :required="required" 
      :value-class="valueClass" 
      @click="selectClick"
    >
    </van-cell>
    <van-popup 
      v-model="showPopup" 
      position="right" 
      :style="{ width: '100%',height: '100%' }"
    >
      <van-nav-bar
        :title="title"
        :right-text="rightText"
        left-arrow
        @click-left="showPopup = false"
        @click-right="onComfirm"
      />
      <!-- 多选 -->
      <!-- <van-loading size="24px" vertical>{{loadingText}}</van-loading> -->
      <template v-if="multiple">
        <van-checkbox-group v-model="valueKeys" class="select-wrapper">
          <van-cell-group>
            <van-cell
              v-for="(item, index) in list"
              clickable
              :key="item.id"
              @click="toggle(index, item)"
            >
              <van-checkbox
                :name="item.id"
                ref="checkboxes"
                shape="square"
              >
                {{item.name}}
              </van-checkbox>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </template>
      <!-- 单选 -->
      <template v-else>
        <van-radio-group v-model="valueKey" class="select-wrapper">
          <van-cell-group>
            <van-cell 
              v-for="item in list" 
              clickable
              :key="item.id" 
              @click="radioClick(item)"
              class="mb-select-popup-cell"
            >
              <van-radio 
                :name="item.id"
                class="md-radio-icon"
              >
                {{item.name}}
              </van-radio>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </template>
    </van-popup>
  </div>
</template>

<script>
import { request } from 'utils/http'
export default {
  name: 'mb-select',
  data() {
    return {
      showPopup: false,
      list: [],
      value:  null,
      value_display:  this.result_display || '',
      valueKey: '', // 单选
      valueKeys: [], // 多选
      placeholder: "请选择",
      error: false,
      visible: true
    }
  },
  props: {
    item: Object,
    result: [String, Array],
    result_display: String,
    multiple: Boolean
  },
  computed: {
    title() {
      return this.item.caption || this.item.name || ''
    },
    required() {
      return this.item.required
    },
    valueClass() {
      return this.value != null && this.value != '' ? 'selected' : (this.error ? 'required': '')
    },
    readonly() {
      return this.item.readonly
    },
    rightText() {
      return this.multiple ? "确定" : ''
    }
  },
  watch: {
    value: function(newVal) {
      if(this.multiple) {
        this.valueKeys = newVal ? newVal.split(',') : [];
      } else {
        this.valueKey = newVal;
      }
      let emitObj = {};
      emitObj[this.item.name] = newVal;
      emitObj[(this.item.name + "_display")] = this.value_display;
      this.$emit("formChange", this.item.name, emitObj, this.item);
    }
  },
  methods: {
    selectClick() {
      if(this.readonly) return
      this.showPopup = true;
      const _this = this;
      request(this.item.url, {
        query: {
          sign: this.item.supportSigns,
          time: this.item.time
        }
      }).then(res => {
        if(res.code !== "0") {
          this.$notify({ type: 'danger', message: '获取' + _this.title + '信息失败' });
          return
        }
        if(res.datas && res.datas.code && res.datas.code.rows) {
          _this.list = res.datas.code.rows;
        }
      })
    },
    radioClick(item) {
      this.error = false;
      // 这个赋值顺序很重要
      this.value_display = item.name;
      this.valueKey = item.id; 
      this.showPopup = false;
      this.value = this.valueKey;
    },
    toggle(index, item) {
      this.$refs.checkboxes[index].toggle();
      let key = this.valueKeys.indexOf(item.id);
      if( key === -1) {
        this.valueKeys.push(item.id)
      } else {
        this.valueKeys.splice(key, 1)
      }
    },
    onComfirm() {
      if(this.valueKeys.length) this.error = false;
      this.showPopup = false;
      let display = [];
      this.list.forEach(opt => {
        if(this.valueKeys.indexOf(opt.id) >-1) display.push(opt.name)
      })
      this.value_display = display.join(',');
      this.value = this.valueKeys.join(',');
    },
    validate() {
      if(this.item.required) {
        if((this.multiple && this.valueKeys.length === 0) || (!this.multiple && this.valueKey === '')) {
          this.error = true;
          return false
        }
      }
      return true
    }
  },
  mounted() {
    let emitObj = {};
    emitObj[this.item.name] = this.result;
    emitObj[(this.item.name + "_display")] = this.result_display;
    this.$emit("formChange", this.item.name, emitObj, this.item);
  }
}
</script>
<style>
  .selected {
    color: #323233;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .required {
    color: #ee0a24;
  }
  .md-radio-icon .van-radio__icon .van-icon {
    background-color: #FFFFFF;
    border-color: transparent;
  }
  .md-radio-icon .van-radio__icon--checked .van-icon {
    color: #1989fa;
  }
  .mb-select-popup-cell .van-radio__label {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .van-cell-clear {
    padding: 0;
    display: block;
  }
  .select-wrapper {
    max-height: calc(100% - 46px);
    overflow: auto;
  }
</style>